// export function debounce(fn: Function, delay = 200) {
//   let timer: ReturnType<typeof setTimeout> | null = null
//   return function () {
//     const _this = this
//     let args = arguments
//     if (!!timer) {
//       clearInterval(timer)
//       timer = null
//     }
//     timer = setTimeout(() => {
//       fn.apply(_this, args);
//     }, delay)
//   }
// }
class Debounced {
  /**
   * @param func 需要包装的函数
   * @param delay 延迟时间，单位ms
   * @param immediate 是否默认执行一次(第一次不延迟)
   */
  use = (func: Function, delay: number = 60, immediate: boolean = false): Function => {
    let timer: ReturnType<typeof setTimeout> | null = null
    return (...args: any) => {
      if (immediate) {
        func.apply(this, args) // 确保引用函数的指向正确，并且函数的参数也不变
        immediate = false
        return
      }
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
      timer = setTimeout(() => {
        func.apply(this, args)
      }, delay)
    }
  }
}
export default Debounced
